﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;


namespace MuYue.ORM.SQLite {
    internal class SqliteHelper : ISqlHelper {

        SQLiteConnection conn;

        private void DebugSql(string sql) {
            Log.LogService.Debug("[SQL输出] {0}", sql);
        }

        public SqliteHelper(string connetionString) {
            conn = new SQLiteConnection(connetionString);
        }

        private bool OpenConnection() {
            if (conn != null) {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();
                return true;
            }
            return false;
        }

        #region ISqlHelper 成员

        public int ExcuteSql(string sql) {
            DebugSql(sql);
            using (var cmd = conn.CreateCommand()) {
                if (OpenConnection()) {
                    cmd.CommandText = sql;
                    return cmd.ExecuteNonQuery();
                }
            }
            return 0;
        }

        public DataSet QueryDataset(string sql) {
            DebugSql(sql);
            using (var cmd = conn.CreateCommand()) {
                cmd.CommandText = sql;
                if (OpenConnection()) {
                    using (var ad = new SQLiteDataAdapter(cmd)) {
                        var ds = new DataSet();
                        ad.Fill(ds);
                        return ds;
                    }
                }
            }
            return null;
        }

        public object QuerySingle(string sql) {
            DebugSql(sql);
            using (var cmd = conn.CreateCommand()) {
                if (OpenConnection()) {
                    cmd.CommandText = sql;
                    return cmd.ExecuteScalar();
                }
            }
            return null;
        }

        #endregion

        #region IDisposable 成员

        public void Dispose() {
            if (conn != null)
                conn.Dispose();
        }

        #endregion
    }
}
